//
//  BSTableViewController.m
//  BaiSiBuDeJie
//
//  Created by bill on 16/8/26.
//  Copyright © 2016年 tsaievan. All rights reserved.
//

#import "BSTableViewController.h"
#import "BSBaseModel.h"
#import "BaseCell.h"
#import "BSWebViewController.h"

@interface BSTableViewController ()
//模型数组
@property(nonatomic,strong)NSArray *dataArray;
@end

@implementation BSTableViewController
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
}

-(void)setUrl:(NSString *)url
{
    _url = url;
    [BSBaseModel downDataWithUrl:url successBlock:^(BSBaseModel *model) {
        
        self.dataArray = (NSMutableArray *)model.list;
        //刷新数据
        [self.tableView reloadData];
        
    } failBlock:^(NSError *err) {
        NSLog(@"下载失败 %@",err);
    }];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    //注册Nib  Cell
    UINib *nib = [UINib nibWithNibName:@"BaseCell" bundle:nil];
    
    [self.tableView registerNib:nib forCellReuseIdentifier:@"tabelViewCell"];
    
    
    //增加广告栏
    [self addADView];
    
    
#pragma mark - 下拉刷新
    //设置刷新的时候展示的图片
    NSArray *idleImages = [NSArray arrayWithObjects:
                           [UIImage imageNamed:@"bdj_mj_refresh_2"],nil];
    
    NSArray *pullingImages = [NSArray arrayWithObject:[UIImage imageNamed:@"bdj_mj_refresh_1"]];
    NSArray *refreshingImages = [NSArray arrayWithObjects:
                                 [UIImage imageNamed:@"bdj_mj_refresh_3"], nil];
    
    
    //创建下拉刷新的实例对象
    MJRefreshGifHeader *header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
        
        [self updata];
        
    }];
    
    //1.设置普通状态的动画图片
    [header setImages:idleImages forState:MJRefreshStateIdle];
    //2.设置即将刷新状态的动画图片（一松开就会刷新的状态）
    [header setImages:pullingImages forState:MJRefreshStatePulling];
    //3.设置正在刷新状态的动画图片
    [header setImages:refreshingImages forState:MJRefreshStateRefreshing];
    
    self.tableView.mj_header = header;
    
#pragma mark --- 自定义刷新状态和刷新时间文字
    // Set title
    [header setTitle:@"下拉可以刷新" forState:MJRefreshStateIdle];
    [header setTitle:@"松开后立即刷新" forState:MJRefreshStatePulling];
    [header setTitle:@"正在刷新 ..." forState:MJRefreshStateRefreshing];
    
    // Set font
    header.stateLabel.font = [UIFont systemFontOfSize:15];
    header.lastUpdatedTimeLabel.font = [UIFont systemFontOfSize:14];
    
    // Set textColor
    header.stateLabel.textColor = [UIColor grayColor];
    header.lastUpdatedTimeLabel.textColor = [UIColor grayColor];
}


#pragma mark - updata

- (void)updata
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager GET:self.url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //下载数据成功,停止刷新
        [self endRefresh];
        
        NSDictionary *dic = responseObject;
        
        BSBaseModel *model =  [BSBaseModel mj_objectWithKeyValues:dic];
        
        self.dataArray = model.list;
        
//        NSLog(@"%lu",(unsigned long)self.dataArray.count);
        
        [self.tableView reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

-(void)endRefresh
{
    [self.tableView.mj_header endRefreshing];
    [self.tableView.mj_footer endRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    BaseCell *cell = [BaseCell getCellWith:tableView];
    
    ListModel *model = self.dataArray[indexPath.row];
    
    cell.model = model;
    
    return cell;
}


- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 350;
}


#pragma mark - 添加广告栏
-(void)addADView
{
    //广告栏
    UIImageView *ADView = [UIImageView new];
    //ADView.contentMode = UIViewContentModeScaleAspectFill;
    ADView.userInteractionEnabled = YES;
    
    self.tableView.tableHeaderView = ADView;
    
    [ADView sd_setImageWithURL:[NSURL URLWithString:@"http://mstatic.spriteapp.cn//ugc/2016/08/18/91EK3H.jpg"]];
    
//    [ADView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.left.right.equalTo(self.tableView.tableHeaderView).offset(0);
//        make.height.offset(80);
//    }];
    
    ADView.frame = CGRectMake(0, 0, self.tableView.bounds.size.width, kScreenW / 5.517);
    
    
    //添加手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(drump)];
    [ADView addGestureRecognizer:tap];
    
}

#pragma mark - 弹webView的block
-(void)drump
{
    self.drumpBlock();
}




//-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
//{
//    
//    return 250;
//}
/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
